﻿namespace WLFramework.Data
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Data;

    /// <summary>
    /// DataTable扩展方法
    /// </summary>
    public static class DataTableExtensions
    {
        /// <summary>
        /// 将DataTable转换为实体类集合
        /// </summary>
        /// <typeparam name="TEntity">实体类类型</typeparam>
        /// <param name="dt">DataTable对象</param>
        /// <returns>转换后结果</returns>
        public static IList<TEntity> ToList<TEntity>(this DataTable dt)
            where TEntity : new()
        {
            Shield.AssertNotNull(ref dt, "dt");
            return dt.CreateDataReader().ToList<TEntity>();
        }

        /// <summary>
        /// 将DataTable第一列的值转换成集合
        /// </summary>
        /// <typeparam name="TValue">列的类型</typeparam>
        /// <param name="dt">DataTable对象</param>
        /// <returns>结果集</returns>
        public static IList<TValue> ToFirstColumnList<TValue>(this DataTable dt)
        {
            Shield.AssertNotNull(ref dt, "dt");
            return dt.CreateDataReader().ToFirstColumnList<TValue>();
        }

        /// <summary>
        /// 根据列名称获取DataTable该列的所有值
        /// </summary>
        /// <typeparam name="TValue">列的类型</typeparam>
        /// <param name="dt">DataTable对象</param>
        /// <param name="name">列名称</param>
        /// <returns>该列的所有值</returns>
        public static IList<TValue> ToListByColumnName<TValue>(this DataTable dt, string name)
        {
            Shield.AssertNotNull(ref dt, "dt");
            return dt.CreateDataReader().ToListByColumnName<TValue>(name);
        }

        /// <summary>
        /// 根据列序号获取DataTable该列的所有值
        /// </summary>
        /// <typeparam name="TValue">列的类型</typeparam>
        /// <param name="dt">DataTable对象</param>
        /// <param name="index">列序号</param>
        /// <returns>该列的所有值</returns>
        public static IList<TValue> ToListByColumnIndex<TValue>(this DataTable dt, int index)
        {
            Shield.AssertNotNull(ref dt, "dt");
            return dt.CreateDataReader().ToListByIndex<TValue>(index);
        }
    }
}
